package com.BaoHua.demo.jwtUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import cn.hutool.core.date.DateUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class JwtHelper {

	private static final String SECRET = "session_secret";
	
	private static final String ISSUER = "mooc_user";
	
	public static String getToken(Map<String,String> claims) {
		Algorithm algorithm = Algorithm.HMAC256(SECRET);
		JWTCreator.Builder builder = JWT.create().withIssuer(ISSUER).withExpiresAt(DateUtil.nextWeek());
		claims.forEach((k,v)->builder.withClaim(k, v));
		return builder.sign(algorithm);
	}
	
	public static Map<String,String> verifyToken(String token){
		Algorithm algorithm = Algorithm.HMAC256(SECRET);
		JWTVerifier verifier = JWT.require(algorithm).withIssuer(ISSUER).build();
		DecodedJWT jwt = verifier.verify(token);
		Map<String, Claim> map = jwt.getClaims();
		Map<String, String> resultMap = new HashMap<String,String>();
		map.forEach((k,v)->resultMap.put(k, v.asString()));
		return resultMap;
	}
	
	public static void main(String[] args) {
//		Map<String,String> claims = new HashMap<String,String>();
//		claims.put("username", "fzh");
//		claims.put("password", "123456");
//		String token = JwtHelper.getToken(claims);
//		System.out.println(token);
//		Map<String, String> verifyToken = JwtHelper.verifyToken("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwYXNzd29yZCI6IjEyMzQ1NiIsImlzcyI6Im1vb2NfdXNlciIsImV4cCI6MTU0ODMxMDkyOCwidXNlcm5hbWUiOiJmemgifQ.GLg7qxylm14aSrqyiMBt6jQU7KSDKlRxZUf9kyHiJXo");
//		System.out.println(verifyToken.get("username")+" "+verifyToken.get("password"));
//	
	
		JwtBuilder jwtBuilder = Jwts.builder()
		.setId("666")
		.setSubject("小冯")
		.setIssuedAt(new Date()).signWith(SignatureAlgorithm.HS256, "itcast")
		.setExpiration(DateUtil.tomorrow())
		.claim("role", "admin").claim("msg","ok");
		System.out.println(jwtBuilder.compact());
		try {
			Claims claims = Jwts.parser().setSigningKey("itcast").parseClaimsJws(jwtBuilder.compact()).getBody();
			System.out.println(claims.getId());
			System.out.println(claims.getSubject());
			System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(claims.getIssuedAt()));
			System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(claims.getExpiration()));
			System.out.println(claims.get("role"));
			System.out.println(claims.get("msg"));
		}catch(Exception e) {
			System.out.println("已经过期");
		}
		
	}

}
